package com.gsp.gspframework.helper;

import com.gsp.gspframework.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class BeanHelper {
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getBeanClassSet();
        BEAN_MAP.putAll(classSet.stream().collect(Collectors.toMap(clz -> clz, clz -> ReflectionUtil.newInstance(clz))));
    }

    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    public static <T> T getBean(Class<?> clz) {
        if (!BEAN_MAP.containsKey(clz)) {
            throw new RuntimeException("can not get bean by class: " + clz);
        }
        return (T) BEAN_MAP.get(clz);
    }

    public static void setBean(Class<?> clz, Object o) {
        BEAN_MAP.put(clz, o);
    }
}
